package A1_二叉树;

import java.util.ArrayList;
import java.util.List;

public class LC_257二叉树的所有路径 {
    public static class TreeNode{
        int val;
        TreeNode left;
        TreeNode right;
        TreeNode(){}
        TreeNode(int val){
            this.val=val;
        }
        TreeNode(int val, TreeNode left, TreeNode right){
            this.val=val;
            this.left=left;
            this.right=right;
        }
    }
    public List<String> binaryTreePaths(TreeNode root) {
        List<String> result=new ArrayList<>();
        if(root==null)
            return result;
        List<Integer> path=new ArrayList<>();
        traversal(root,path,result);
        return result;
    }
    public static void traversal(TreeNode node,List<Integer> path,List<String> result){
        path.add(node.val);//中
        if(node.left==null && node.right==null){
            StringBuilder sb=new StringBuilder();
            for(int i=0;i<path.size()-1;i++){
                sb.append(path.get(i)+"->");
            }
            sb.append(path.get(path.size()-1));
            result.add(String.valueOf(sb));
            return;
        }
        //左
        if(node.left!=null){
            traversal(node.left,path,result);
            path.remove(path.size()-1);
        }
        //右
        if(node.right!=null){
            traversal(node.right,path,result);
            path.remove(path.size()-1);
        }
    }
}
